const blocks = document.querySelectorAll('.block');
let selectedBlock = null;
let offsetX, offsetY;

// 为每个方块添加鼠标事件
blocks.forEach(block => {
    block.addEventListener('mousedown', (e) => {
        selectedBlock = block;
        offsetX = e.offsetX;
        offsetY = e.offsetY;
        block.style.cursor = 'grabbing';
    });

    document.addEventListener('mousemove', (e) => {
        if (selectedBlock) {
            const boardRect = document.querySelector('.board').getBoundingClientRect();
            let x = e.clientX - boardRect.left - offsetX;
            let y = e.clientY - boardRect.top - offsetY;

            // 确保方块不会超出棋盘边界
            const maxX = boardRect.width - selectedBlock.clientWidth;
            const maxY = boardRect.height - selectedBlock.clientHeight;
            x = Math.max(0, Math.min(x, maxX));
            y = Math.max(0, Math.min(y, maxY));

            selectedBlock.style.transform = `translate(${x}px, ${y}px)`;
        }
    });

    document.addEventListener('mouseup', () => {
        if (selectedBlock) {
            // 吸附到最近的网格
            const boardRect = document.querySelector('.board').getBoundingClientRect();
            let x = parseFloat(selectedBlock.style.transform.split('(')[1]);
            let y = parseFloat(selectedBlock.style.transform.split(',')[1]);
            const gridSize = 100;
            const snappedX = Math.round(x / gridSize) * gridSize;
            const snappedY = Math.round(y / gridSize) * gridSize;
            selectedBlock.style.transform = `translate(${snappedX}px, ${snappedY}px)`;
            selectedBlock.style.cursor = 'grab';
            selectedBlock = null;
        }
    });
});
